const path = require('path');
const webpack = require('webpack');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');


module.exports = {
  mode: 'development',
  entry: {
    index: {
      // webpack 打包入口
      import: './src/index.js',
    },
    react: ['react'],
    "react-dom": ['react-dom'],
    "react-router-dom": ['react-router-dom'],
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: '[name].[chunkhash].js',
    publicPath: '/',
    asyncChunks: true,
    chunkFilename: `[name].[contenthash:8].async.js`
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json'],
    alias: {
      '@': path.resolve(__dirname,'src')
    }
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: {
          loader: 'babel-loader',
          options: {
            exclude: /node_modules/,
            cacheDirectory: true
          }
        }
      },
      {
        test: /\.html$/,
        use: {
          loader: 'html-loader'
        }
      },
      // 配置处理.css文件的第三方loader规则
      {
        test: /\.css$/,
        use: ['style-loader','css-loader'],
        include: /src/
      },
      // 配置处理.less文件的第三方loader规则
      {
        test: /\.less$/,
        use: ['style-loader','css-loader', 'less-loader'],
        include: /src/
      },
      // 配置处理.scss文件的第三方loader规则
      {
        test: /\.scss$/,
        use: ['style-loader','css-loader', 'sass-loader'],
        include: /src/
      }
    ]
  },
  optimization: {
    chunkIds: 'deterministic',
    minimize: true,
    minimizer: [
      new TerserPlugin({
        // 压缩文件
        terserOptions: {
          format: {
            comments: false,
            max_line_len: true,
            beautify: true,
            ascii_only: true,
            preserve_annotations: true
          }
        },
        extractComments: false
      })
    ],
    splitChunks: {
      chunks: 'all'
    }
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new HtmlWebPackPlugin({
      inject: true,
      title: 'react app',
      // 使用指定html作为模板，在文件中引入打包后的资源文件
      template: path.join(__dirname, './public/index.html'),
      filename: 'index.html'
    }),
    new CleanWebpackPlugin(),
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash:8].css',
      chunkFilename: '[id].[contenthash:8].chunk.css'
    })
  ],
  devServer: {
    server: 'http',
    static: {
      directory: path.join(__dirname, '/'),
      watch: {
        ignored: '*.jsx',
        usePolling: false
      },
      serveIndex: true
    },
    allowedHosts: ['.host.com'],
    port: '3000',
    hot: true,
    historyApiFallback: true
  }
}